package edu.clarkson.ee368.spring2012.coreservices;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/account")
public class AccountServlet extends HttpServlet {

	private static final long serialVersionUID = 2511864203760907966L;

	@EJB
	private AccountDAO accountDAO;

	public AccountServlet() {
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String action = req.getParameter("action");
		if ("register".equals(action)) {
			try {
				Long accountId = accountDAO.createAccount(username, password);
				HttpSession session = req.getSession();
				session.setAttribute("accountId", accountId);
				resp.setStatus(HttpServletResponse.SC_CREATED);
			} catch (AccountAlreadyExistsException ex) {
				resp.setStatus(HttpServletResponse.SC_CONFLICT);
			}
		}
		else if ("login".equals(action)) {
			Account account = accountDAO.getAccountFromUserPass(username, password);
			if (account != null) {
				HttpSession session = req.getSession();
				Long accountId = account.getId();
				session.setAttribute("accountId", accountId);
				String sessionId = session.getId();
				System.out.println(sessionId);
				resp.setStatus(HttpServletResponse.SC_OK);
			}
			else {
				resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
			}
		}

		
	}

	@Override
	protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		HttpSession session = req.getSession();
		String sessionId = session.getId();
		System.out.println(sessionId);
		Long accountId = (Long) session.getAttribute("accountId");
		System.out.println(accountId);
		session.removeAttribute("accountId");
		session.invalidate();
		resp.setStatus(HttpServletResponse.SC_OK);
	}
	
	

}
